package com.qing.demo.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * @author caozhipeng
 * @date 2025/7/25
 * 编码器
 */
public class MyEncoder extends MessageToByteEncoder {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        String msg=o.toString();
        byte[] bytes=msg.getBytes(Charset.forName("utf-8"));

        byte[] send=new byte[bytes.length+2];
        System.arraycopy(bytes,0,send,1,bytes.length);
        send[0]=0x02;
        send[send.length-1]=0x03;

        byteBuf.writeInt(send.length);
        byteBuf.writeBytes(send);
    }
}